/**
 * Copyright &copy; 2016 CNJSON All rights reserved.
 */
package com.hongsuan.pplive.modules.cms.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.cnjson.common.beanvalidator.BeanValidators;
import com.cnjson.common.config.Global;
import com.cnjson.db.persistence.Page;
import com.cnjson.common.utils.StringUtils;
import com.cnjson.common.web.BaseController;
import com.hongsuan.pplive.common.utils.excel.ExportExcel;
import com.hongsuan.pplive.common.utils.excel.ImportExcel;
import com.hongsuan.pplive.modules.cms.entity.UserCourse;
import com.hongsuan.pplive.modules.cms.service.UserCourseScoreService;

/**
 * 课程成绩管理Controller
 * @author Susan
 * @version 2015-11-30
 */
@Controller
@RequestMapping(value = "${adminPath}/cms/userCourseScore")
public class UserCourseScoreController extends BaseController {

	@Autowired
	private UserCourseScoreService scoreService;

    @ModelAttribute
    public UserCourse get(UserCourse userCourse) {
        UserCourse entity = null;
        if (StringUtils.isNotBlank(userCourse.getId()) && StringUtils.isNoneBlank(userCourse.getCourseId())){
            entity = scoreService.get(userCourse);
        }
        if (entity == null){
            entity = new UserCourse();
        }
        return entity;
    }

	@RequiresPermissions("cms:userCourseScore:view")
	@RequestMapping(value = {"list", ""})
	public String list(UserCourse userCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<UserCourse> page = scoreService.findPage(new Page<UserCourse>(request, response), userCourse);
		model.addAttribute("page", page);
		return "modules/cms/userCourseScoreList";
	}

	@RequiresPermissions("cms:userCourseScore:view")
	@RequestMapping(value = "form")
	public String form(UserCourse userCourse, Model model) {
        UserCourse userCourse1 = get(userCourse);
		model.addAttribute("userCourse", userCourse1);
		return "modules/cms/userCourseScoreForm";
	}

	@RequiresPermissions("cms:userCourseScore:edit")
	@RequestMapping(value = "save")
	public String save(UserCourse userCourse, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, userCourse)){
			return form(userCourse, model);
		}
        String[] courseIds = userCourse.getCourseId().split(",");
        for(String courseId : courseIds) {
            userCourse.setCourseId(courseId);
            scoreService.save(userCourse);
        }

		addMessage(redirectAttributes, "提交学员成绩成功");
		return "redirect:"+Global.getAdminPath()+"/cms/userCourseScore/?repage";
	}

	@RequiresPermissions("cms:userCourseScore:edit")
	@RequestMapping(value = "delete")
	public String delete(UserCourse userCourse, RedirectAttributes redirectAttributes) {
		scoreService.delete(userCourse);
		addMessage(redirectAttributes, "删除学员成绩成功");
		return "redirect:"+Global.getAdminPath()+"/cms/userCourseScore/?repage";
	}


    /**
     * 导入学员成绩数据
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("cms:userCourseScore:edit")
    @RequestMapping(value = "import", method= RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<UserCourse> list = ei.getDataList(UserCourse.class);
            for (UserCourse userCourse : list){
                try{
                    scoreService.save(userCourse);

                    successNum++;
                }catch(ConstraintViolationException ex){
                    failureMsg.append("<br/>学员ID "+userCourse.getId()+" 导入失败：");
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList){
                        failureMsg.append(message+"; ");
                        failureNum++;
                    }
                }catch (Exception ex) {
                    failureMsg.append("<br/>学员ID "+userCourse.getId()+" 导入失败："+ex.getMessage());
                }
            }
            if (failureNum>0){
                failureMsg.insert(0, "，失败 "+failureNum+" 条学员成绩，导入信息如下：");
            }
            addMessage(redirectAttributes, "已成功导入 "+successNum+" 条学员成绩"+failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入学员成绩失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/cms/userCourseScore/list?repage";
    }

    /**
     * 下载导入学员成绩数据模板
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("cms:userCourseScore:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "学员成绩导入模板.xlsx";
            UserCourse userCourse = new UserCourse();
            userCourse.setExamDate(new Date());
            List<UserCourse> list = new ArrayList<UserCourse>();
            list.add(userCourse);
            new ExportExcel("学员成绩", UserCourse.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
        }
        return "redirect:" + adminPath + "/cms/userCourseScore/list?repage";
    }

}